// 云函数入口文件
const cloud = require('wx-server-sdk')

// 初始化 cloud
cloud.init({
  // API 调用都保持和云函数当前所在环境一致
  env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
let $ = db.command.aggregate

// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openid = wxContext.OPENID
  console.log('openid == :', openid)
  switch(event.methodName){
    case 'getActive':
      return  getActive(event.activeId)
      break
      case 'getMyActive':

        return  getMyActive({
          openid , 
          pageNum:event.pageNum , 
          pageSize:event.pageSize, 
          content: event.content
        })
        break
      case 'getMyJoinActive':
         return  getMyJoinActive(openid , event.pageNum , event.pageSize)
          break
      case 'getCollectActiveList':
        return  getCollectActiveList(event)
      break
  }
 
}

const getActive = async (activeId) => {

  var result = await db.collection('active').aggregate()
              .match({
                _id: activeId 
              })
          
              .end()
      return result;
}
const getMyActive = async ({openid,pageNum,pageSize, content}) => {
  var skip = (pageNum - 1) * pageSize
  var matchObj = {
    openid: openid
  }
  if(content){
    matchObj.content = db.RegExp({
      regexp: content,
      options: 'im',
    })
  }
  return await db.collection('active').aggregate()
  .match(matchObj)
  .sort({
      createDate: -1
  })
  .skip(skip)
  
  .limit(pageSize)

  .end()
}
const getMyJoinActive = async (openid,pageNum,pageSize) => {
  var skip = (pageNum - 1) * pageSize
  return await db.collection('join').aggregate()
  .match({
    openid: openid 
  })
  .sort({
    createDate: -1
  })
  .skip(skip)
 
  .limit(pageSize)

  .end()
}

const getCollectActiveList = async (event) => {
  var skip = (event.pageNum - 1) * event.pageSize
    var limit = event.pageSize
  
    let params = {
      openid: event.openid
    }

    console.log('getCollectActiveList:', params)
    let res = await db.collection('collect').aggregate()
      .match(params)
      .skip(skip)
      .limit(limit)
      .lookup({
        from: 'active',
        localField: "activeId",
        foreignField: "_id",
        as: "activeList"
      })
      .replaceRoot({
        newRoot: $.mergeObjects([$.arrayElemAt(['$activeList', 0]), '$$ROOT'])
      })
      .project({
        activeList: 0
      })
      .end()
    return res.list
}